import { _decorator, Component, Node, Label, director } from 'cc';
import { GameEvent, GameManager } from './GameManager';

const { ccclass, property } = _decorator;

@ccclass('ScoreManager')
export class ScoreManager extends Component {
    private scoreLabel!: Label;

    onLoad() {
        this.scoreLabel = this.getComponent(Label)!;
        this.updateScore;
    }

    start() {
        // 监听分数更新事件
        this.node.on(GameEvent.SCORE_UPDATED, this.updateScore, this);
        // 监听游戏重置事件
        this.node.parent.on(GameEvent.GAME_RESET, this.resetScore, this);
    }

    // 更新分数显示
    private updateScore(score: number, target: number) {
        this.scoreLabel.string = `分数: ${score}/${target}`;
    }

    // 重置分数显示
    private resetScore() {
        // 从GameManager获取目标分数（或通过事件传递）
    const gameManager = director.getScene().getChildByName("GameManager")?.getComponent(GameManager);
    const target = gameManager?.targetScore || 0;
    this.scoreLabel.string = `分数: 0/${target}`;
    }

    onDestroy() {
        this.node.off(GameEvent.SCORE_UPDATED, this.updateScore, this);
        this.node.parent.off(GameEvent.GAME_RESET, this.resetScore, this);
    }
}
